package com.sc.nft.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.common.collect.Lists;
import com.sc.nft.dao.*;
import com.sc.nft.entity.*;
import com.sc.nft.entity.dto.MaintainUserConSignCollectionPageDTO;
import com.sc.nft.entity.vo.*;
import com.sc.nft.enums.*;
import com.sc.nft.exception.GlobalRunTimeException;
import com.sc.nft.pool.UserPool;
import com.sc.nft.service.SecondCollectionService;
import com.sc.nft.service.ShowLevelService;
import com.sc.nft.service.UserCollectionService;
import com.sc.nft.sup.ErrorCode;
import com.sc.nft.sup.PageRequest;
import com.sc.nft.util.BigDecimalUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 寄售表服务接口实现
 *
 * @author kancy
 * @description 由 Mybatisplus Code Generator 创建
 * @since 2022-10-05 00:23:53
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class SecondCollectionServiceImpl implements SecondCollectionService {

    private final SecondCollectionDao secondCollectionDao;

    private final UserCollectionDao userCollectionDao;

    private final ExitConsensusUserDao exitConsensusUserDao;
    private final UserConsensusDao userConsensusDao;
    private final UserCollectionConsensusDao userCollectionConsensusDao;

    private final UserCollectionService userCollectionService;

    private final CatenaInfoDao catenaInfoDao;

    private final SecondCollectionConfigDao secondCollectionConfigDao;

    private final ShowLevelService showLevelService;

    private final UserCreatorInfoDao userCreatorInfoDao;

    private final StaticDataDao staticDataDao;

    private final DigitalCollectionDao digitalCollectionDao;

    private final SecondOrderDao secondOrderDao;

    private final RedisTemplate redisTemplate;

    private final CycleCollectionDao cycleCollectionDao;


    @Override
    public ConditionQueryListVO conditionQueryList() {
        List<ShowLevelVO> showLevelVOList = showLevelService.getAllShowLevelByApp();
        List<UserCreatorVO> UserCreatorList = userCreatorInfoDao.getUserCreatorList();
        Collections.reverse(UserCreatorList);
        ConditionQueryListVO conditionQueryListVO = new ConditionQueryListVO();
        conditionQueryListVO.setUserCreatorList(UserCreatorList);
        conditionQueryListVO.setShowLevelList(showLevelVOList);
        return conditionQueryListVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void offShelf(SecondCollection secondCollection) {
        if (secondCollection.getStatus() == ConSignStatus.LOCK) {
            throw new GlobalRunTimeException("该藏品已被锁定，无法取消");
        }

        secondCollection.setStatus(ConSignStatus.CANCEL);
//        secondCollection.updateById();
        secondCollectionDao.updateById(secondCollection);
        userCollectionDao.setConsignStatus(secondCollection.getUserCollectionId(), CollectionOnConsignEnum.NORMAL);
        if (secondCollection.getMarketType() == MarketTypeEnum.BRAND_INCUBATION) {
            redisTemplate.opsForList().remove(RedisKeyEnum.SECOND_SALES_COLLECTION.getKey() + secondCollection.getCollectionId().toString(), 1, secondCollection.getId().toString());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void conSign(Long userCollectionId, BigDecimal salesPrice, String payPwd) {
        //获取藏品信息
        UserCollection userCollection = userCollectionService.getById(userCollectionId);
        //1.藏品不为空 2.藏品用户与登录用户相同 3.藏品是持有状态
        if (ObjectUtil.isNull(userCollection) || userCollection.getUserId().longValue() != UserPool.getUser().getId().longValue() || BooleanUtil.isFalse(userCollection.getIsHold())) {
            throw new GlobalRunTimeException(ErrorCode.COLLECTION_NOT_FOUND);
        }
        if (userCollection.getIsSmeltingOnly()) {
            throw new GlobalRunTimeException(ErrorCode.IS_SMELTING_ONLY);
        }

        // 锁仓中
        if (userCollection.getLockedPositionTime() != null && userCollection.getLockedPositionTime().after(DateUtil.date())) {
            throw new GlobalRunTimeException(ErrorCode.LOCK_COLLECTION);
        }
        //藏品需要先上链
        if (userCollection.getStatus() != ChainStatusEnum.ONLINE) {
            throw new GlobalRunTimeException(ErrorCode.COLLECTION_NOT_ONLINE);
        }
        //查询可寄售藏品的配置
        SecondCollectionConfig secondCollectionConfig = secondCollectionConfigDao.getByCollectionId(userCollection.getCollectionId());
        if (NumberUtil.isGreater(salesPrice, secondCollectionConfig.getMaxPrice()) || NumberUtil.isLess(salesPrice, secondCollectionConfig.getMinPrice())) {
            throw new GlobalRunTimeException("出售价格不正确");
        }
        //配置不为空 并且藏品配置是可寄售状态
        if (ObjectUtil.isNull(secondCollectionConfig) || BooleanUtil.isFalse(secondCollectionConfig.getStatus())) {
            throw new GlobalRunTimeException(ErrorCode.NOT_CON_SIGN);
        }
        if (secondCollectionConfig.getMarketType() != MarketTypeEnum.BRAND_INCUBATION) {
            throw new GlobalRunTimeException(ErrorCode.PARAM_ERROR);
        }

        //查询当前藏品是否是寄售状态
        SecondCollection secondCollection = secondCollectionDao.getOnShelfUserCollectionId(userCollectionId);
        if (ObjectUtil.isNotNull(secondCollection)) {
            throw new GlobalRunTimeException(ErrorCode.ON_CON_SIGN);
        }
        //如果藏品价格大于0
        if (secondCollectionConfig.getStartPrice().compareTo(BigDecimal.ZERO) > 0) {
            //判断传入价格 是否在可寄售的价格区间内
            if (!(secondCollectionConfig.getMinPrice().compareTo(salesPrice) <= 0 && secondCollectionConfig.getMaxPrice().compareTo(salesPrice) >= 0)) {
                throw new GlobalRunTimeException(ErrorCode.CON_SIGN_PRICE_ERROR);
            }
        }
        DigitalCollection digitalCollection = digitalCollectionDao.getById(userCollection.getCollectionId());
        if (ObjectUtil.isNull(digitalCollection)) {
            throw new GlobalRunTimeException(ErrorCode.COLLECTION_NOT_FOUND);
        }

        secondCollection = new SecondCollection();
        secondCollection.setCollectionId(userCollection.getCollectionId());
        secondCollection.setUserCollectionId(userCollection.getId());
        secondCollection.setUserId(userCollection.getUserId());
        secondCollection.setShareProfitPanelId(secondCollectionConfig.getShareProfitPanelId());
        secondCollection.setCollectionSumCount(digitalCollection.getSumCount());
        secondCollection.setNumbering(userCollection.getNumbering());
        secondCollection.setStatus(ConSignStatus.ON_SALES);
        secondCollection.setOnShelfTime(DateTime.now());
        secondCollection.setOffShelfTime(DateUtil.endOfDay(secondCollection.getOnShelfTime()));
        BigDecimal charge = salesPrice.multiply(secondCollectionConfig.getCharge()).setScale(2, BigDecimal.ROUND_DOWN);
        secondCollection.setCharge(charge);
        secondCollection.setMinPrice(secondCollectionConfig.getMinPrice());
        secondCollection.setMaxPrice(secondCollectionConfig.getMaxPrice());
        secondCollection.setSalesPrice(salesPrice);
        if (BooleanUtil.isTrue(userCollection.getAntiHoardFlag())) {
            secondCollection.setAntiHoardPrice(userCollection.getAntiHoardPrice());
        } else {
            secondCollection.setAntiHoardPrice(BigDecimal.ZERO);
        }
        secondCollectionDao.save(secondCollection);
        userCollectionDao.setConsignStatus(userCollectionId, CollectionOnConsignEnum.ON_SALES);
        if (secondCollectionConfig.getMarketType() == MarketTypeEnum.BRAND_INCUBATION) {
            String key = RedisKeyEnum.SECOND_SALES_COLLECTION.getKey() + secondCollection.getCollectionId().toString();
            redisTemplate.opsForList().rightPush(key, secondCollection.getId().toString());
            redisTemplate.expire(key, getTodayEndSecond(), TimeUnit.SECONDS);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void conSignForFreeMarket(Long userCollectionId, BigDecimal salesPrice, String payPwd) {
        //获取藏品信息
        UserCollection userCollection = userCollectionService.getById(userCollectionId);
        //1.藏品不为空 2.藏品用户与登录用户相同 3.藏品是持有状态
        if (ObjectUtil.isNull(userCollection) || userCollection.getUserId().longValue() != UserPool.getUser().getId().longValue() || BooleanUtil.isFalse(userCollection.getIsHold())) {
            throw new GlobalRunTimeException(ErrorCode.COLLECTION_NOT_FOUND);
        }
        if (userCollection.getIsSmeltingOnly()) {
            throw new GlobalRunTimeException(ErrorCode.IS_SMELTING_ONLY);
        }

        // 锁仓中
        if (userCollection.getLockedPositionTime() != null && userCollection.getLockedPositionTime().after(DateUtil.date())) {
            throw new GlobalRunTimeException(ErrorCode.LOCK_COLLECTION);
        }
        //藏品需要先上链
        if (userCollection.getStatus() != ChainStatusEnum.ONLINE) {
            throw new GlobalRunTimeException(ErrorCode.COLLECTION_NOT_ONLINE);
        }
        //查询可寄售藏品的配置
        SecondCollectionConfig secondCollectionConfig = secondCollectionConfigDao.getByCollectionId(userCollection.getCollectionId());
        if (NumberUtil.isGreater(salesPrice, secondCollectionConfig.getMaxPrice()) || NumberUtil.isLess(salesPrice, secondCollectionConfig.getMinPrice())) {
            throw new GlobalRunTimeException("出售价格不正确");
        }
        //配置不为空 并且藏品配置是可寄售状态
        if (ObjectUtil.isNull(secondCollectionConfig) || BooleanUtil.isFalse(secondCollectionConfig.getStatus())) {
            throw new GlobalRunTimeException(ErrorCode.NOT_CON_SIGN);
        }
        if (secondCollectionConfig.getMarketType() != MarketTypeEnum.FREE_MARKET) {
            throw new GlobalRunTimeException(ErrorCode.PARAM_ERROR);
        }

        //查询当前藏品是否是寄售状态
        SecondCollection secondCollection = secondCollectionDao.getOnShelfUserCollectionId(userCollectionId);
        if (ObjectUtil.isNotNull(secondCollection)) {
            throw new GlobalRunTimeException(ErrorCode.ON_CON_SIGN);
        }
        //如果藏品价格大于0
        if (secondCollectionConfig.getStartPrice().compareTo(BigDecimal.ZERO) > 0) {
            //判断传入价格 是否在可寄售的价格区间内
            if (!(secondCollectionConfig.getMinPrice().compareTo(salesPrice) <= 0 && secondCollectionConfig.getMaxPrice().compareTo(salesPrice) >= 0)) {
                throw new GlobalRunTimeException(ErrorCode.CON_SIGN_PRICE_ERROR);
            }
        }
        DigitalCollection digitalCollection = digitalCollectionDao.getById(userCollection.getCollectionId());
        if (ObjectUtil.isNull(digitalCollection)) {
            throw new GlobalRunTimeException(ErrorCode.COLLECTION_NOT_FOUND);
        }

        secondCollection = new SecondCollection();
        secondCollection.setCollectionId(userCollection.getCollectionId());
        secondCollection.setUserCollectionId(userCollection.getId());
        secondCollection.setUserId(userCollection.getUserId());
        secondCollection.setShareProfitPanelId(secondCollectionConfig.getShareProfitPanelId());
        secondCollection.setCollectionSumCount(digitalCollection.getSumCount());
        secondCollection.setNumbering(userCollection.getNumbering());
        secondCollection.setStatus(ConSignStatus.ON_SALES);
        secondCollection.setOnShelfTime(DateTime.now());
        secondCollection.setOffShelfTime(DateUtil.endOfDay(secondCollection.getOnShelfTime()));
        BigDecimal charge = salesPrice.multiply(secondCollectionConfig.getCharge()).setScale(2, BigDecimal.ROUND_DOWN);
        secondCollection.setCharge(charge);
        secondCollection.setMinPrice(secondCollectionConfig.getMinPrice());
        secondCollection.setMaxPrice(secondCollectionConfig.getMaxPrice());
        secondCollection.setSalesPrice(salesPrice);
        secondCollection.setMarketType(MarketTypeEnum.FREE_MARKET);
        if (BooleanUtil.isTrue(userCollection.getAntiHoardFlag())) {
            secondCollection.setAntiHoardPrice(userCollection.getAntiHoardPrice());
        } else {
            secondCollection.setAntiHoardPrice(BigDecimal.ZERO);
        }
        secondCollectionDao.save(secondCollection);
        userCollectionDao.setConsignStatus(userCollectionId, CollectionOnConsignEnum.ON_SALES);

    }

    private long getTodayEndSecond() {
        DateTime now = DateTime.now();
        DateTime end = DateUtil.endOfDay(now);
        return DateUtil.between(now, end, DateUnit.SECOND);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchConSign(List<Long> userCollectionIds, BigDecimal salesPrice, String payPwd) {
        for (Long userCollectionId : userCollectionIds) {
            conSign(userCollectionId, salesPrice, payPwd);
        }
    }

    /**
     * 市值批量操作专用  价格为区间随机
     *
     * @param userCollectionIds
     * @param payPwd
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchConSignForMaintain(List<Long> userCollectionIds, BigDecimal lowPrice, BigDecimal highPrice, String payPwd) {
        for (Long userCollectionId : userCollectionIds) {
            conSignForFreeMarket(userCollectionId, BigDecimalUtils.getRandomBigDecimal(lowPrice, highPrice), payPwd);
        }
    }

    @Override
    public SecondCollectionDetailVO getDetailById(Long id) {
        SecondCollectionDetailVO collectionDetail = new SecondCollectionDetailVO();
        SecondCollection secondCollection = secondCollectionDao.getById(id);

        if (secondCollection.getMarketType() != MarketTypeEnum.FREE_MARKET && secondCollection.getMarketType() != MarketTypeEnum.COPYRIGHT) {
            throw new GlobalRunTimeException(ErrorCode.PARAM_ERROR);
        }

        UserCollection userCollection = userCollectionDao.getById(secondCollection.getUserCollectionId());
        collectionDetail.setId(secondCollection.getId());
        collectionDetail.setCollectionId(userCollection.getId());
        //藏品
        DigitalCollection digitalCollection = digitalCollectionDao.getById(userCollection.getCollectionId());
        collectionDetail.setFirstTitle(digitalCollection.getFirstTitle());
        collectionDetail.setProductDetailPicture(digitalCollection.getProductDetailPicture());
        collectionDetail.setProductDetailPictureType(digitalCollection.getProductDetailPictureType());
        collectionDetail.setProductPresentation(digitalCollection.getProductPresentation());
        collectionDetail.setCreationContent(digitalCollection.getCreationContent());
        collectionDetail.setModelImg(digitalCollection.getModelImg());
        collectionDetail.setModelDistance(digitalCollection.getModelDistance());
        String privilegePresentation = digitalCollection.getPrivilegePresentation();
        if (ObjectUtil.isEmpty(privilegePresentation)) {
            privilegePresentation = "";
        }
        collectionDetail.setPrivilegePresentation(privilegePresentation);
        collectionDetail.setProductCount(digitalCollection.getSumCount());
        //作者
        UserCreatorInfo userCreatorInfo = userCreatorInfoDao.getById(digitalCollection.getUserCreatorId());
        collectionDetail.setNickName(userCreatorInfo.getDaoName());
        collectionDetail.setCreatorAvatarImg(userCreatorInfo.getCreatorAvatarImg());
        //系列
        CatenaInfo catenaInfo = catenaInfoDao.getById(digitalCollection.getCatenaId());
        collectionDetail.setCatenaName(catenaInfo.getName());
        //最新成交价
//        BigDecimal newPrice = userCollectionDao.getNewPrice(userCollection.getCollectionId());
        BigDecimal newPrice = secondOrderDao.getLastPrice(userCollection.getCollectionId());
        newPrice = ObjectUtil.isNull(newPrice) ? BigDecimal.ZERO : newPrice;
        collectionDetail.setNewPrice(digitalCollection.getNewDeal().toPlainString());
        Integer circulationNum = userCollectionDao.getCirculationNumByCollectionId(digitalCollection.getId());

        Integer sumCount = digitalCollection.getSumCount();
        Integer sumCirculationNum = digitalCollection.getCirculationNum() + circulationNum;
        if (sumCount < sumCirculationNum) {
            sumCirculationNum = sumCount;
        }
        collectionDetail.setCirculationNum(sumCirculationNum);
        collectionDetail.setCirculationCount(digitalCollection.getCirculationCount());
        StaticData staticData = staticDataDao.getByType("purchase_notes");
        collectionDetail.setPurchaseNotes(staticData.getValue());
        collectionDetail.setIsGive(digitalCollection.getIsGive());
        collectionDetail.setThreeModelId(digitalCollection.getThreeModelId());
        collectionDetail.setChainStatus(0);
        Boolean isGive = Boolean.FALSE;
        Long between = 0L;
//        Date createTime = userCollection.getCreateTime();
//        if (ObjectUtil.isEmpty(createTime)) {
//            createTime = userCollection.getModifyTime();
//        }
//        if (digitalCollection.getIsGive()) {
//            isGive = Boolean.TRUE;
//            if (ObjectUtil.isNotEmpty(createTime)) {
//                DateTime dateTime = DateUtil.offsetDay(createTime, digitalCollection.getLockupDays());
//                if (DateTime.now().after(dateTime)) {
//                    isGive = Boolean.TRUE;
//                } else {
//                    isGive = Boolean.FALSE;
//                    between = dateTime.between(DateTime.now(), DateUnit.MS);
//                }
//            }
//        }
        //获取链信息
        CollectionChainDetailDTO collectionChainDetail = userCollectionService.getCollectionChainDetail(userCollection);
        collectionDetail.setTianheChain(collectionChainDetail.getTianheChain());
        collectionDetail.setChainUrl(collectionChainDetail.getChainUrl());

        Boolean isCancel = Boolean.FALSE;
        //如果当前的藏品是自己的  就是可以取消
        if (secondCollection.getUserId().intValue() == UserPool.getUser().getId().intValue()) {
            isCancel = Boolean.TRUE;
        }
        collectionDetail.setIsCancel(isCancel);
        collectionDetail.setIsGive(isGive);
        collectionDetail.setCountdown(between);
        collectionDetail.setNumbering(userCollection.getNumbering() + "/" + digitalCollection.getSumCount());
        collectionDetail.setOnShelfTime(secondCollection.getOnShelfTime());
        collectionDetail.setSalesPrice(secondCollection.getSalesPrice().setScale(2, BigDecimal.ROUND_DOWN).toPlainString());

        BigDecimal issuePrice = digitalCollection.getIssuePrice();
        issuePrice = ObjectUtil.isNull(issuePrice) ? BigDecimal.ZERO : issuePrice;
        String buyPrice = issuePrice.setScale(2, BigDecimal.ROUND_DOWN).toPlainString();
//        String issuePrice = digitalCollection.getIssuePrice().setScale(2, BigDecimal.ROUND_DOWN).toPlainString();
        collectionDetail.setIssuePrice(buyPrice);
        collectionDetail.setSkipUrl(digitalCollection.getSkipUrl());
        collectionDetail.setConsensusNum("0.0");
        collectionDetail.setIsConsensusCollection(false);
        if (digitalCollection.getCollectionType() == DigitalMarketTypeEnum.ECOLOGY) {
            ExitConsensusUser exitConsensusUser = exitConsensusUserDao.getByUserId(UserPool.getUser().getId());
            if (ObjectUtil.isNotNull(exitConsensusUser) && exitConsensusUser.getStatus()) {
                UserCollectionConsensus userCollectionConsensus = userCollectionConsensusDao.getBuyUserIdAndCollectionId(UserPool.getUser().getId(), digitalCollection.getId());
                collectionDetail.setConsensusNum(ObjectUtil.isNull(userCollectionConsensus)?"0.0":userCollectionConsensus.getConsensusNum().toPlainString());
                collectionDetail.setIsConsensusCollection(true);
            }
        }
        return collectionDetail;
    }

    @Override
    public SecondCollectionDetailV3_7VO freeMarketDetails_v3_7(Long id) {
        SecondCollectionDetailV3_7VO secondCollectionDetail = new SecondCollectionDetailV3_7VO();

        // 根据配置id,获取藏品的配置信息
        SecondCollectionConfig secondCollectionConfig = secondCollectionConfigDao.getById(id);
        if (BeanUtil.isEmpty(secondCollectionConfig)) {
            throw new GlobalRunTimeException("该藏品无法寄售");
        }
        if (secondCollectionConfig.getMarketType() != MarketTypeEnum.FREE_MARKET && (secondCollectionConfig.getMarketType() != MarketTypeEnum.COPYRIGHT)) {
            throw new GlobalRunTimeException(ErrorCode.PARAM_ERROR);
        }

        // 通过配置id获取藏品信息
        secondCollectionDetail.setCollectionId(secondCollectionConfig.getCollectionId());
        // 通过藏品id获取藏品信息
        DigitalCollection digitalCollection = digitalCollectionDao.getById(secondCollectionConfig.getCollectionId());
        secondCollectionDetail.setFirstTitle(digitalCollection.getFirstTitle());
        secondCollectionDetail.setSumCount(digitalCollection.getSumCount());
        secondCollectionDetail.setProductDetailPicture(digitalCollection.getProductDetailPicture());
        secondCollectionDetail.setProductDetailPictureType(digitalCollection.getProductDetailPictureType());
        secondCollectionDetail.setProductPresentation(digitalCollection.getProductPresentation());
        UserCreatorInfo userCreatorInfo = userCreatorInfoDao.getById(digitalCollection.getUserCreatorId());
        secondCollectionDetail.setNickName(userCreatorInfo.getDaoName());
        secondCollectionDetail.setCreatorAvatarImg(userCreatorInfo.getCreatorAvatarImg());
        StaticData staticData = staticDataDao.getByType("purchase_notes");
        secondCollectionDetail.setPurchaseNotes(staticData.getValue());
        CatenaInfo catenaInfo = catenaInfoDao.getById(digitalCollection.getCatenaId());
        secondCollectionDetail.setCatenaName(catenaInfo.getName());
        String privilegePresentation = digitalCollection.getPrivilegePresentation();
        if (ObjectUtil.isEmpty(privilegePresentation)) {
            privilegePresentation = "";
        }
        secondCollectionDetail.setPrivilegePresentation(privilegePresentation);
        secondCollectionDetail.setCountdown(0L);
        secondCollectionDetail.setNowDate(DateUtil.now());
        secondCollectionDetail.setThreeModelId(digitalCollection.getThreeModelId());
        secondCollectionDetail.setCreationContent(digitalCollection.getCreationContent());
        secondCollectionDetail.setModelImg(digitalCollection.getModelImg());
        secondCollectionDetail.setModelDistance(digitalCollection.getModelDistance());
        secondCollectionDetail.setMarketTypeEnum(secondCollectionConfig.getMarketType());
        secondCollectionDetail.setIsLockedPosition(secondCollectionConfig.getIsLockedPosition());
        secondCollectionDetail.setLockedPositionType(secondCollectionConfig.getLockedPositionType());
        secondCollectionDetail.setLockedPositionHour(secondCollectionConfig.getLockedPositionHour());
        secondCollectionDetail.setLockedPositionTime(secondCollectionConfig.getLockedPositionTime());
        secondCollectionDetail.setLockedPositionDescribe();
        return secondCollectionDetail;
    }

    @Override
    public BrandMarketDetailsVO brandMarketDetails(Long id) {
        String key = StrUtil.format("brandMarketDetails:{}", id);
        int hour = DateUtil.date().hour(true);
        //在10点到12点之间才调用缓存
        if (11 <= hour && hour < 13) {
            Boolean hasKey = redisTemplate.hasKey(key);
            if (hasKey) {
                return JSON.parseObject(Convert.toStr(redisTemplate.opsForValue().get(key)), BrandMarketDetailsVO.class);
            }
        }
        BrandMarketDetailsVO brandMarketDetailsVO = new BrandMarketDetailsVO();
        //二级商品信息
        SecondCollectionConfig collectionConfig = secondCollectionConfigDao.getById(id);

        if (ObjectUtil.isNull(collectionConfig)) {
            throw new GlobalRunTimeException(ErrorCode.PARAM_ERROR);
        }

        if (collectionConfig.getMarketType() != MarketTypeEnum.BRAND_INCUBATION) {
            throw new GlobalRunTimeException(ErrorCode.PARAM_ERROR);
        }
        //藏品信息
        DigitalCollection digitalCollection = digitalCollectionDao.getById(collectionConfig.getCollectionId());
        //作者
        UserCreatorInfo userCreatorInfo = userCreatorInfoDao.getById(digitalCollection.getUserCreatorId());
        //系列
        CatenaInfo catenaInfo = catenaInfoDao.getById(digitalCollection.getCatenaId());
        //藏品id
        brandMarketDetailsVO.setCollectionId(digitalCollection.getId());
        brandMarketDetailsVO.setFirstTitle(digitalCollection.getFirstTitle());
        //总库存
        brandMarketDetailsVO.setProductCount(digitalCollection.getSumCount());
        //系列名称
        brandMarketDetailsVO.setCatenaName(catenaInfo.getName());
        //作者名称
        brandMarketDetailsVO.setNickName(userCreatorInfo.getDaoName());
        brandMarketDetailsVO.setCreatorAvatarImg(userCreatorInfo.getCreatorAvatarImg());
        //藏品图片
        brandMarketDetailsVO.setProductDetailPicture(digitalCollection.getProductDetailPicture());
        brandMarketDetailsVO.setProductDetailPictureType(digitalCollection.getProductDetailPictureType());
        brandMarketDetailsVO.setProductPresentation(digitalCollection.getProductPresentation());
        brandMarketDetailsVO.setPrivilegePresentation(digitalCollection.getPrivilegePresentation());
        brandMarketDetailsVO.setThreeModelId(digitalCollection.getThreeModelId());
        brandMarketDetailsVO.setCreationContent(digitalCollection.getCreationContent());
        brandMarketDetailsVO.setModelImg(digitalCollection.getModelImg());
        brandMarketDetailsVO.setModelDistance(digitalCollection.getModelDistance());
        brandMarketDetailsVO.setSkipUrl(digitalCollection.getSkipUrl());
        brandMarketDetailsVO.setSalesPrice(collectionConfig.getMaxPrice().setScale(2, BigDecimal.ROUND_DOWN).toPlainString());
        //2023年5月22日13:31:47 为了banner跳转兼容,把ID反带回去
        brandMarketDetailsVO.setConfigId(id);
        //寄售信息
        String startPrice = collectionConfig.getStartPrice().setScale(2, BigDecimal.ROUND_DOWN).toPlainString();
        //起始价
        brandMarketDetailsVO.setStartPrice(startPrice);
        String upRatio = collectionConfig.getUpRatio().multiply(new BigDecimal("100")).setScale(2, BigDecimal.ROUND_DOWN).toPlainString();
        //增长率
        brandMarketDetailsVO.setUpRatio(upRatio + "%");
        brandMarketDetailsVO.setUpRatioNew("±" + upRatio + "%");
        //开始时间
        brandMarketDetailsVO.setCreateTime(collectionConfig.getCreateTime());
        //说明
        brandMarketDetailsVO.setConsignExplanation(collectionConfig.getConsignExplanation());

        brandMarketDetailsVO.setIsLockedPosition(collectionConfig.getIsLockedPosition());
        brandMarketDetailsVO.setLockedPositionType(collectionConfig.getLockedPositionType());
        brandMarketDetailsVO.setLockedPositionHour(collectionConfig.getLockedPositionHour());
        brandMarketDetailsVO.setLockedPositionTime(collectionConfig.getLockedPositionTime());
        brandMarketDetailsVO.setLockedPositionDescribe();
        //11点到13点才存缓存
        if (11 <= hour && hour < 13) {
            redisTemplate.opsForValue().set(key, JSON.toJSONString(brandMarketDetailsVO), 60, TimeUnit.MINUTES);
        }
        return brandMarketDetailsVO;
    }

    @Override
    public List<BrandMarketHistoryDetailsVO> brandMarketHistoryDetails(Long collectionId) {
        String key = StrUtil.format("brandMarketHistoryDetails:{}", collectionId);
        Boolean hasKey = redisTemplate.hasKey(key);
        if (hasKey) {
            return JSON.parseArray(Convert.toStr(redisTemplate.opsForValue().get(key)), BrandMarketHistoryDetailsVO.class);
        }
        List<BrandMarketHistoryDetailsVO> brandMarketHistoryDetailsVOS = secondOrderDao.brandMarketHistoryDetails(collectionId);
        List<BrandMarketHistoryDetailsVO> list = Lists.newArrayList();
        for (BrandMarketHistoryDetailsVO brandMarketHistoryDetailsVO : brandMarketHistoryDetailsVOS) {
            BigDecimal price = brandMarketHistoryDetailsVO.getPrice();
            brandMarketHistoryDetailsVO.setPriceString(price.setScale(2, BigDecimal.ROUND_DOWN).toPlainString());
            list.add(brandMarketHistoryDetailsVO);
        }
        redisTemplate.opsForValue().set(key, JSON.toJSONString(list), 180, TimeUnit.MINUTES);
        return list;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertCycleCollection(CycleCollectionEnum type) {
        if (type == CycleCollectionEnum.ZHI_TAN) {
            List<ZhiTanArtListVO> datas = digitalCollectionDao.getArtList();
            if (CollUtil.isEmpty(datas)) {
                return;
            }
            cycleCollectionDao.deleteByType(type);
            for (ZhiTanArtListVO data : datas) {
                CycleCollection cycleCollection = new CycleCollection();
                //智探Api定时任务插入更新时type = 1
                cycleCollection.setType(type.getCode());
                cycleCollection.setDataKey(data.getId().toString());
                cycleCollection.setDataValue(JSON.toJSONString(data));
                cycleCollection.setOrderByKey(data.getId().toString());
                cycleCollection.insert();
            }
        }
        if (type == CycleCollectionEnum.DING_LIAN) {
            List<LargeDiskAccessVO> all = Lists.newArrayList();
            List<LargeDiskAccessVO> datas = digitalCollectionDao.getLargeDiskAccessDataNotEcology();
            List<LargeDiskAccessVO> datas1 = digitalCollectionDao.getLargeDiskAccessDataInEcology();
            all.addAll(datas);
            all.addAll(datas1);
            if (CollUtil.isEmpty(all)) {
                return;
            }
            cycleCollectionDao.deleteByType(type);
            for (LargeDiskAccessVO data : all) {
                CycleCollection cycleCollection = new CycleCollection();
                //盯链Api定时任务插入更新时type = 2
                cycleCollection.setType(type.getCode());
                cycleCollection.setDataKey(data.getCollectionId().toString());
                cycleCollection.setDataValue(JSON.toJSONString(data));
                cycleCollection.setOrderByKey(data.getCollectionId().toString());
                cycleCollection.insert();
            }
        }

    }

    @Override
    public List<ZhiTanArtListVO> artList(Integer page, Integer pageSize) {
        List<CycleCollection> cycleCollections = digitalCollectionDao.artList(page, pageSize);
        return cycleCollections.stream().map(c -> {
            if (ObjectUtil.isNull(c.getDataValue())) {
                return new ZhiTanArtListVO();
            }
            return JSON.parseObject(c.getDataValue(), ZhiTanArtListVO.class);
        }).collect(Collectors.toList());
    }

    @Override
    public IPage<UserCreatorVO> getAuthorList(PageRequest request) {
        return userCreatorInfoDao.getAuthorList(request);
    }

    @Override
    public IPage<MaintainUserConSignCollectionPageDTO> getMainTainConSignCollection(int pageNo, int pageSize, Long userId,
                                                                                    BigDecimal lowPrice, BigDecimal highPrice,
                                                                                    Long collectionId) {
        return secondCollectionDao.maintainUserConsignPage(pageNo, pageSize, userId, lowPrice, highPrice, collectionId);
    }

    @Override
    public ZhiTanArtInfoVO artInfo(Integer collectionId) {
        CycleCollection cycleCollection = digitalCollectionDao.artInfo(collectionId);
        if (ObjectUtil.isNull(cycleCollection.getDataValue())) {
            return new ZhiTanArtInfoVO();
        }
        return JSON.parseObject(cycleCollection.getDataValue(), ZhiTanArtInfoVO.class);
    }
}